package com.mypackage.diary.dao.security;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mypackage.diary.model.Userprofile;

@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Userprofile loadUserByEmail(String email) throws HibernateException {

		Session session = sessionFactory.openSession();
		if (session == null) {
			System.out.println("Get session success");
		}
		Transaction tx = null;

		String sql = " select u.*,r.*  from userprofile u,authority r where u.IdRole = r.idauthority and u.Email =:email ";

		try {
			System.out.println("email : " + email);

			tx = session.beginTransaction();
			
			System.out.println("connected : " + session.isConnected());
		
			
			Userprofile userProfile = (Userprofile) session.createSQLQuery(sql)
					.addEntity(Userprofile.class).setParameter("email", email).uniqueResult();
			
			System.out.println("+++++++++++++++++++++");
			System.out.println(userProfile.getAuthority().getIdauthority()+ " "+userProfile.getAuthority().getRole());
			return userProfile;

		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

}
